package com.bdqn.springcache.controller;

import com.bdqn.springcache.entity.Book;
import com.bdqn.springcache.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;


@Controller
public class BookController {

    @Autowired
    private BookService bookService;

    @GetMapping("/books")
    public ModelAndView findAllBooks() {
        System.out.println("books----");
        List<Book> books = bookService.findAllBooks();

        ModelAndView mv = new ModelAndView();
        mv.addObject("books", books);
        mv.setViewName("books");
        return mv;
    }

    @GetMapping("/books/{id}")
    public ModelAndView findStudentById(@PathVariable("id") int id) {
        Book book = bookService.findBookById(id);
        ModelAndView mv = new ModelAndView();
        mv.addObject("book", book);
        mv.setViewName("book");
        return mv;

    }

    @PostMapping("/addBook")
    public ModelAndView addStudent(Book book) {
        bookService.addBook(book);
        ModelAndView mv = new ModelAndView();
        mv.setViewName("redirect:/books");//添加成功后，跳转到查找所有学生的控制器
        return mv;
    }

    @GetMapping("/addBook")
    public String addStudent() {
        return "addBook";
    }

    @GetMapping("/deleteBook/{id}")
    public ModelAndView deleteStudent(@PathVariable("id") int id) {
        bookService.deleteBook(id);
        ModelAndView mv = new ModelAndView();
        mv.setViewName("redirect:/books");//删除成功后，跳转到查找所有学生的控制器
        return mv;
    }

    @GetMapping("/updateBook/{id}")
    public ModelAndView toUpdateStudent(@PathVariable("id") int id) {
        Book book = bookService.findBookById(id);
        ModelAndView mv = new ModelAndView();
        mv.addObject("book", book);
        mv.setViewName("updateBook");
        return mv;
    }

    @PostMapping("/updateBook")
    public ModelAndView UpdateStudent(Book book) {

        bookService.updateBook(book);
        ModelAndView mv = new ModelAndView();
        mv.setViewName("redirect:/books");//修改成功后，跳转到查找所有学生的控制器
        return mv;
    }


//    @GetMapping("/searchBooks")
//    public ModelAndView searchBooks(Book book){
//        System.out.println(book);
//        List<Book> books=bookService.searchBooks(book);
//        System.out.println("遍历books");
//        for(Book b:books){
//            System.out.println(b);
//        }
//        ModelAndView mv=new ModelAndView();
//        mv.addObject("books",books);
//        mv.setViewName("books");
//        return mv;
//    }


}
